<!-- 新增/修改弹框 -->
<template>
  <!-- 新增/修改弹窗 -->
  <el-dialog v-model="dialogAddOrEdit.visible" :width="screenWidth" :fullscreen="mobile === 'mobile'"
    :title="dialogAddOrEdit.title" draggable close-icon="CloseBold" :close-delay="200" style="margin-top: 5vh"
    @close="closeDialog(false)">
    <el-form ref="addOrEditFormRef" v-loading="loading" :model="formData" :rules="rules" label-width="170" size=""
      style="padding-right: 10px; overflow: auto">
      <el-row justify="start" style="margin-top: 10px">
        <el-col v-if="currentSystem == 'SysUser'" :span="itemSpan">
          <el-form-item label="项目名称" prop="projectName">
            <el-input v-model="formData.projectName" readonly placeholder="请输入项目名称" />
            <el-button v-if="currentSystem == 'SysUser'" type="primary" plain style="position: absolute; right: -60px"
              @click="handleSelectProject">选择</el-button>
          </el-form-item>
        </el-col>
        <el-col :span="itemSpan">
          <el-form-item label="所属企业" prop="corpName">
            <el-select v-model="formData.corpName" :disabled="dialogAddOrEdit.title == '续签'" placeholder="请选择" clearable
              @change="changeCorp">
              <el-option v-for="item in corps" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="dialogAddOrEdit.title == '续签' ? itemSpan : itemSpan - 2">
          <el-form-item label="姓名" prop="personName">
            <el-input v-model="formData.personName" placeholder="请选择人员" readonly
              :disabled="dialogAddOrEdit.title == '续签'" />
          </el-form-item>
        </el-col>
        <el-col v-if="dialogAddOrEdit.title != '续签'" :span="2">
          <el-button type="primary" style="float: right" plain @click="handleSelectPerson">选择</el-button>
        </el-col>

        <el-col :span="itemSpan">
          <el-form-item label="合同编号" prop="code">
            <el-input v-model="formData.code" placeholder="请输入合同编号" />
          </el-form-item>
        </el-col>
        <el-col :span="itemSpan">
          <el-form-item label="合同类型" prop="type">
            <el-select v-model="formData.type" placeholder="请选择" clearable>
              <el-option v-for="item in contractTypes" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="itemSpan">
          <el-form-item label="合同签订日期" prop="signingDate">
            <el-date-picker v-model="formData.signingDate" type="date" format="YYYY-MM-DD" value-format="YYYY-MM-DD"
              placeholder="选择日期" />
          </el-form-item>
        </el-col>
        <el-col :span="itemSpan">
          <el-form-item label="合同起始日期" prop="startDate">
            <el-date-picker v-model="formData.startDate" type="date" :disabled="dialogAddOrEdit.title == '续签'"
              format="YYYY-MM-DD" value-format="YYYY-MM-DD" placeholder="选择日期" @change="formData.endDate = undefined" />
          </el-form-item>
        </el-col>
        <el-col :span="itemSpan">
          <el-form-item label="合同终止日期" prop="endDate">
            <el-date-picker v-model="formData.endDate" type="date" format="YYYY-MM-DD" value-format="YYYY-MM-DD"
              placeholder="选择日期" :disabled-date="disabledEndDate" />
          </el-form-item>
        </el-col>

        <el-col :span="itemSpan">
          <el-form-item label="工资计算方式" prop="salaryCalculationMethod">
            <el-select v-model="formData.salaryCalculationMethod" placeholder="请选择" clearable>
              <el-option v-for="item in salaryCalculationMethods" :key="item.value" :label="item.label"
                :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="itemSpan">
          <el-form-item label="工资标准" prop="wageStandard">
            <!-- <el-input v-model="formData.wageStandard" type="number" placeholder="请输入工资标准" /> -->
            <money-input v-model="formData.wageStandard" unit="元"></money-input>
          </el-form-item>
        </el-col>
        <el-col :span="itemSpan">
          <el-form-item label="工资支付日期" prop="salaryPaymentDate">
            <el-input v-model="formData.salaryPaymentDate" type="number" max="31" placeholder="请输入支付日期" />
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="上传合同附件" prop="attachments">
            <el-upload v-model:file-list="fileList" :action="actionUrl" multiple :limit="5"
              accept=".doc,.docx,.pdf,.jpg,.png,.xls,.xlsx" :on-exceed="handleUploadExceed"
              :on-success="handleUploadSuccess" :on-preview="handleUploadPreview">
              <el-button plain size="small">上传附件</el-button>
              <DownloadTemplate :type="100"></DownloadTemplate>
              <template #tip>
                <div class="el-upload__tip">仅支持上传doc,docx,xls,xlsx,pdf,jpg,png且不大于5M的文件</div>
              </template>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
      <select-project :dialog-select="dialogSelectProject" @select-send-close="projectSendClose"></select-project>
      <select-person :dialog-select="dialogSelectPerson" @select-send-close="personSendClose"></select-person>
    </el-form>

    <template #footer>
      <div class="dialog_footer">
        <el-button type="primary" :loading="loading" @click="handleSubmit">{{ dialogAddOrEdit.footBtn }}</el-button>
        <el-button @click="closeDialog(false)">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import MoneyInput from "@/components/MoneyInput/index.vue";
import { Except, Ride } from "@/utils/decimal";
import { CreatePersonContract, UpdatePersonContract, GetPersonContractForm } from "@/api/contract/index";
import { PersonContractForm } from "@/api/contract/types";
import { getDicts } from "@/store/modules/dict";
import { useScreen } from "@/store/modules/screen";
import { FormRules } from "element-plus/es/components/form/src/types";
import type { UploadUserFile } from "element-plus";
import SelectProject from "@/views/common/SelectProject/index.vue";
// import SelectPerson from "@/views/common/SelectPerson/index.vue";
import SelectPerson from "@/views/common/SelectPersonByProjectCorp/index.vue";
import { getProjectCorps } from "@/api/group/index";
import moment from "moment";
import DownloadTemplate from "@/views/common/DownloadTemplate/index.vue";

const currentSystem = ref(localStorage.getItem("usertypeName"));
const isLumpContractor = ref(localStorage.getItem("isLumpContractor"));

//声明变量
const actionUrl = ref(`${import.meta.env.VITE_APP_BASE_API}/api/v1/common/upload`);
//合同类型
const contractTypes = getDicts("contractType");
//工资计算方式
const salaryCalculationMethods = getDicts("salaryCalculationMethod");
// 参建单位列表（需要从API获取）
const corps = ref();
//上传文件列表
const fileList = ref<UploadUserFile[]>([]);
const screenStore = useScreen();
const mobile = computed(() => screenStore.device);
const screenWidth = ref(900);
const itemSpan = ref(12);
const props = defineProps({
  dialogAddOrEdit: {
    type: Object,
    default: () => ({
      visible: false,
      title: "新增",
      footBtn: "确认新增",
      id: 0,
    }),
  },
});
const formData = reactive<PersonContractForm>({
  attachments: [],
});
//声明缓存键
const cacheKey = ref("personContractForm");
//声明缓存实体
const cacheEntity = ref({
  date: moment().format("YYYYMMDD"),
  serialNumber: 0,
  cacheForm: {
    type: undefined,
    signingDate: undefined,
    startDate: undefined,
    endDate: undefined,
    salaryCalculationMethod: undefined,
    wageStandard: undefined,
    salaryPaymentDate: undefined,
  }
})

//重置缓存表单
const initCacheForm = () => {
  var cacheJson = localStorage.getItem(cacheKey.value);
  if (cacheJson) {
    var temp = JSON.parse(cacheJson);
    if (temp.date == cacheEntity.value.date) {
      cacheEntity.value = temp;
    }
  }
  Object.assign(formData, cacheEntity.value.cacheForm);
};
//更新缓存表单
watchEffect(() => {
  cacheEntity.value.cacheForm.type = formData.type;
  cacheEntity.value.cacheForm.signingDate = formData.signingDate;
  cacheEntity.value.cacheForm.startDate = formData.startDate;
  cacheEntity.value.cacheForm.endDate = formData.endDate;
  cacheEntity.value.cacheForm.salaryCalculationMethod = formData.salaryCalculationMethod;
  cacheEntity.value.cacheForm.wageStandard = formData.wageStandard;
  cacheEntity.value.cacheForm.salaryPaymentDate = formData.salaryPaymentDate;
});
//保存需要保存的表单
const saveCacheForm = () => {
  console.log("保存缓存表单");
  localStorage.setItem(cacheKey.value, JSON.stringify(cacheEntity.value));
};

const { dialogAddOrEdit } = toRefs(props);
const emit = defineEmits(["sendClose"]);
const loading = ref(false);

const addOrEditFormRef = ref(ElForm);

const dialogSelectProject = reactive({
  visible: false,
  title: "选择项目",
  footBtn: "确认",
  id: 0,
  type: "allproject",
});

//结束时间禁用范围
const disabledEndDate = (time: Date) => {
  if (formData.startDate) {
    return time.getTime() <= new Date(formData.startDate).getTime();
  }
};

const handleSelectProject = function () {
  dialogSelectProject.visible = true;
};
const projectSendClose = function (info: any) {
  dialogSelectProject.visible = false;
  if (info) {
    formData.projectId = info.projectId;
    formData.projectName = info.projectName;
    formData.corpName = undefined;
    formData.corpId = undefined;
  }
};

const dialogSelectPerson = reactive({
  visible: false,
  title: "选择人员",
  footBtn: "确认",
  id: 0,
  corpId: 0,
});
const handleSelectPerson = function () {
  if (formData.corpId == undefined || formData.corpId == 0) {
    ElMessage.warning("请选择企业");
    return;
  }
  dialogSelectPerson.corpId = formData.corpId;
  dialogSelectPerson.visible = true;
};
const personSendClose = function (info: any) {
  dialogSelectPerson.visible = false;
  if (info) {
    formData.personId = info.personId;
    formData.personName = info.name;
  }
};

//改变选择单位回调
const changeCorp = function (val: any) {
  let temp = corps.value.filter((item: { value: string }) => item.value == val);
  console.log(val);
  console.log(temp);
  if (temp.length > 0) {
    formData.corpId = temp[0].value;
    formData.corpName = temp[0].label;
    formData.personName = undefined;
    formData.personId = undefined;
    return;
  }
};

//表单验证规则
const validatorAttachment = function (rule: any, value: any, callback: any) {
  if (fileList.value.length == 0) {
    callback(new Error("请上传附件!"));
    return;
  } else {
    callback();
  }
};
const rules = reactive<FormRules<PersonContractForm>>({
  corpName: [{ required: true, message: "请选择企业", trigger: "blur" }],
  personName: [{ required: true, message: "请选择人员", trigger: "blur" }],
  type: [{ required: true, message: "请选择合同类型", trigger: "blur" }],
  signingDate: [{ required: true, message: "合同签订日期不能为空", trigger: "blur" }],
  startDate: [{ required: true, message: "合同起始日期不能为空", trigger: "blur" }],
  endDate: [
    { required: true, message: "合同终止日期不能为空", trigger: "blur" },
    {
      trigger: "blur",
      validator: (rule: any, value: any, callback: any) => {
        if (moment(value).isBefore(formData.startDate)) {
          formData.endDate = undefined;
          return callback(new Error("合同终止日期不能早于合同签订日期"));
        }
        callback();
      },
    },
  ],
  salaryCalculationMethod: [{ required: true, message: "工资计算方式不能为空", trigger: "blur" }],
  wageStandard: [{ required: true, message: "工资标准不能为空", trigger: "blur" }],
  salaryPaymentDate: [
    { required: true, message: "工资发放日期不能为空", trigger: "blur" },
    {
      trigger: "blur",
      validator: (rule: any, value: any, callback: any) => {
        if (parseInt(value) > 31) {
          formData.salaryPaymentDate = undefined;
          return callback(new Error("工资发放日期不能大于31天"));
        }
        if (parseInt(value) == 0) {
          formData.salaryPaymentDate = undefined;
          return callback(new Error("工资发放日期不能为0天"));
        }
        callback();
      },
    },
  ],
  code: [{ required: true, message: "合同编号不能为空", trigger: "blur" }],
  attachments: [
    {
      required: true,
      message: "请上传项目文件",
      trigger: "blur",
      validator: validatorAttachment,
    },
  ],
});

/* 附件上传 */
const handleUploadPreview = (file: any) => {
  ElMessage.info(file.url);
};
const handleUploadExceed = () => {
  ElMessage.error("最多上传5个附件");
};
const handleUploadSuccess = (response: any) => {
  if (response.type === 0) {
    if (response.success) {
    } else {
      ElMessage.error(response.msg);
    }
  } else {
    ElMessage.error(response.msg);
  }
};

function initScreen() {
  if (mobile.value === "mobile") {
    screenWidth.value = screenStore.screenWidth;
    itemSpan.value = 24;
  } else {
    screenWidth.value = 900;
    itemSpan.value = 12;
  }
}

const initCorps = async function () {
  let res = await getProjectCorps();
  if (res.type === 0) {
    if (res.success) {
      corps.value = res.data;
    } else {
    }
  } else {
  }
};
if (currentSystem.value != "SysUser") {
  initCorps();
}

//通过缓存实体获取递增编码
const getCodeByCache = () => {
  let code = moment().format("YYYYMMDD");
  cacheEntity.value.serialNumber++;
  let num = cacheEntity.value.serialNumber;
  if (num < 10) {
    return code + "00000" + num;
  }
  if (num < 100) {
    return code + "0000" + num;
  }
  if (num < 1000) {
    return code + "000" + num;
  }
  if (num < 10000) {
    return code + "00" + num;
  }
  if (num < 100000) {
    return code + "0" + num;
  }
  return code + num;
}

const initForm = async function () {
  initCacheForm();
  if (dialogAddOrEdit.value.id) {
    loading.value = true;
    let res = await GetPersonContractForm(dialogAddOrEdit.value.id);
    loading.value = false;
    if (res.type === 0) {
      if (res.success) {
        Object.assign(formData, res.data);
        if (dialogAddOrEdit.value.title == "续签") {
          formData.startDate = moment(res.data.endDate).add(1, "days").format("YYYY-MM-DD");
          formData.endDate = undefined;
        }
        if (res.data.attachments) {
          let list = Array<any>();
          res.data.attachments.forEach((item: any) => {
            list.push({
              name: item.attachmentName,
              url: item.objectFilePath,
              status: "success",
              uid: item.attachmentId,
            });
          });
          fileList.value = list;
        }
      } else {
      }
    } else {
    }
  }
  else {
    formData.code = getCodeByCache();
  }
};

onMounted(async () => {
  initScreen();
  fileList.value = [];
  initForm();
});

/**
 * 关闭弹窗
 */
function closeDialog(needRefresh: boolean) {
  emit("sendClose", needRefresh);
  resetForm();
}

/**
 * 重置表单
 */
function resetForm() {
  // addOrEditFormRef.value.resetFields();
  // addOrEditFormRef.value.clearValidate();
  formData.personId = undefined;
  formData.personName = undefined;
  fileList.value = [];
  formData.code = getCodeByCache();
}

/**
 * 项目表单提交
 */
function handleSubmit() {
  addOrEditFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      if (fileList.value.length > 0) {
        formData.attachments = new Array<any>();
        fileList.value.forEach((item: any) => {
          if (item.status === "success") {
            if (item.response) {
              formData.attachments.push({ attachmentId: item.response.data });
            } else {
              formData.attachments.push({ attachmentId: item.uid });
            }
          }
        });
      }
      if ((dialogAddOrEdit.value.id || dialogAddOrEdit.value.id > 0) && dialogAddOrEdit.value.title == "续签") {
        formData.signingType = 2;
        CreatePersonContract(formData)
          .then((res) => {
            if (res.type != 0 || res.success) return;
            closeDialog(true);
          })
          .finally(() => (loading.value = false));
      } else if (dialogAddOrEdit.value.id || dialogAddOrEdit.value.id > 0) {
        UpdatePersonContract(formData)
          .then((res) => {
            if (res.type != 0 || res.success) return;
            closeDialog(true);
          })
          .catch((e) => {
            console.log(e);
          })
          .finally(() => (loading.value = false));
      } else {
        formData.signingType = 1;
        CreatePersonContract(formData)
          .then((resp) => {
            if (resp.type != 0 || !resp.success) return;
            saveCacheForm();
            ElMessageBox.confirm("是否继续添加？", "提示", {
              confirmButtonText: "继续",
              cancelButtonText: "否",
            }).then(() => {
              resetForm();
            })
              .catch(() => {
                closeDialog(true);
              });
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}
</script>

<style lang="scss" scoped>
:deep(.el-form-item) {
  flex-wrap: wrap;
}

:deep(.el-input) {
  width: 100%;
}

:deep(.el-select) {
  width: 100%;
}

:deep(.el-cascader) {
  width: 100%;
}

:deep(.el-input__wrapper) {
  width: 100%;
}

:deep(.el-form-item__label) {
  color: #696868;
  font-size: 13px;
}

:deep(.el-upload__tip) {
  display: inline-block;
  margin-left: 10px;
}
</style>
